<?php

namespace library;
//微信小店
use GuzzleHttp\Client;
use support\Redis;

class wx_shop
{


    //获取Access token
    public static function get_access_token()
    {
        if ($access_token = Redis::get('wx_shop_access_token')) {
            return $access_token;
        }
        $appid = env('WX_SHOP_APPID');
        $secret = env('WX_SHOP_SECRET');

        $client = new Client();
        $url = 'https://api.weixin.qq.com/cgi-bin/token?appid=' . $appid . '&secret=' . $secret. '&grant_type=client_credential';
        $res = $client->request('GET', $url);
        $data = json_decode($res->getBody(), true);
        if (isset($data['access_token'])) {
            Redis::set('wx_shop_access_token', $data['access_token'], 'EX', 7000);
        }
        return $data['access_token'] ?? null;
    }


    //-----------------------------------------微信小店------------------------------------------------------//
    //获取订单列表
    public static function get_order_list($page = 1, $page_size = 10)
    {

        $access_token = self::get_access_token();

        if (!$access_token) {
            return ['err' => '获取 access_token 失败'];
        }

        $url = "https://api.weixin.qq.com/channels/ec/order/list/get?access_token={$access_token}";

        $payload = [
            'create_time_range' => [
                'start_time' => time() - 3600 * 24 * 7,
                'end_time' => time()
            ],
            'page_size' => 10,
        ];
        $client = new Client();
        $response = $client->post($url, [
            'json' => $payload
        ]);

        return json_decode($response->getBody()->getContents(), true);


    }


    //获取订单列表
    public static function get_order($order_id)
    {

        $access_token = self::get_access_token();

        if (!$access_token) {
            return ['err' => '获取 access_token 失败'];
        }

        $url = "https://api.weixin.qq.com/channels/ec/order/get?access_token={$access_token}";

        $payload = [
            'order_id' => $order_id,
        ];
        $client = new Client();
        $response = $client->post($url, [
            'json' => $payload
        ]);

        return json_decode($response->getBody()->getContents(), true);


    }




}